package com.hengtongxing.hejiayun.mine;


import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseFragment;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.OrderCountBean;
import com.hengtongxing.hejiayun.bean.UserInfoBean;
import com.hengtongxing.hejiayun.event.UpDateNameEvent;
import com.hengtongxing.hejiayun.homepage.model.HomePageModelImpl;
import com.hengtongxing.hejiayun.homepage.model.IHomePageModel;
import com.hengtongxing.hejiayun.login.LoginActivity;
import com.hengtongxing.hejiayun.mine.model.IMineModel;
import com.hengtongxing.hejiayun.mine.model.MineModelImpl;
import com.hengtongxing.hejiayun.shop.ShopMyOrderListActivity;
import com.hengtongxing.hejiayun.utils.CallPhoneUtil;
import com.hengtongxing.hejiayun.utils.SPManager;
import com.hengtongxing.hejiayun.widget.CommonNoTitleDialog;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 我的
 */
public class MineFragment extends BaseFragment {
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.ll_order_1)
    LinearLayout llOrder1;
    @BindView(R.id.ll_order_2)
    LinearLayout llOrder2;
    @BindView(R.id.ll_order_3)
    LinearLayout llOrder3;
    @BindView(R.id.ll_order_4)
    LinearLayout llOrder4;
    @BindView(R.id.ll_house)
    LinearLayout llHouse;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.ll_exit)
    LinearLayout llExit;
    @BindView(R.id.tv_order_1)
    TextView tvOrder1;
    @BindView(R.id.tv_order_2)
    TextView tvOrder2;
    @BindView(R.id.tv_integral_value)
    TextView tvIntegralValue;
    @BindView(R.id.ll_integral_list)
    LinearLayout llIntegralList;
    @BindView(R.id.ll_about_us)
    LinearLayout llAboutUs;
    @BindView(R.id.tv_telphone)
    TextView tvTelphone;
    @BindView(R.id.ll_kefu_mobile)
    LinearLayout llKefuMobile;
    private Unbinder unbinder;
    private UserInfoBean userInfoBean;
    private CommonNoTitleDialog.Builder dialogBuild;
    private IHomePageModel homePageModel;
    private IMineModel mineModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();
    }


    public void initView() {
        mineModel = new MineModelImpl();
        homePageModel = new HomePageModelImpl();
        requestUserInfo();
        requestOrderCount();
    }

    /**
     * 用户信息
     */
    public void requestUserInfo() {
        mineModel.requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {
                userInfoBean = bean;
                tvName.setText(userInfoBean.getData().getName());
                if (!TextUtils.isEmpty(userInfoBean.getData().getMobile()) && userInfoBean.getData().getMobile().length() == 11) {
                    String mobile = userInfoBean.getData().getMobile().substring(0, 3) + "****" + userInfoBean.getData().getMobile().substring(7, 11);
                    tvMobile.setText(mobile);
                } else {
                    tvMobile.setText(userInfoBean.getData().getMobile());
                }
                tvIntegralValue.setText(userInfoBean.getData().getCan_integral() + "积分");
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestOrderCount() {
        mineModel.requestOrderCount(new DataCallBack<OrderCountBean>() {
            @Override
            public void onSuccessful(OrderCountBean bean) {
                if (bean.getData().getStatus1() > 0) {
                    tvOrder1.setVisibility(View.VISIBLE);
                    tvOrder1.setText(String.valueOf(bean.getData().getStatus1()));
                } else {
                    tvOrder1.setVisibility(View.GONE);
                }
                if (bean.getData().getStatus6() > 0) {
                    tvOrder2.setVisibility(View.VISIBLE);
                    tvOrder2.setText(String.valueOf(bean.getData().getStatus6()));
                } else {
                    tvOrder2.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @Subscribe
    public void onUpDateNameEvent(UpDateNameEvent event) {
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
        if (userInfoBean != null) {
            tvName.setText(userInfoBean.getData().getName());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestUserInfo();
        requestOrderCount();
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestUserInfo();
            requestOrderCount();
        }
    }

    @OnClick({R.id.ll_kefu_mobile, R.id.ll_integral_list, R.id.ll_about_us, R.id.ll_order_1, R.id.ll_order_2, R.id.ll_order_3, R.id.ll_order_4, R.id.ll_house, R.id.ll_address, R.id.ll_setting, R.id.ll_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_integral_list:
                skipToActivity(IntegralListActivity.class);
                break;
            case R.id.ll_order_1:
                Intent intent = new Intent(mActivity, ShopMyOrderListActivity.class);
                intent.putExtra("selectPosition", 1);
                startActivity(intent);
                break;
            case R.id.ll_order_2:
                intent = new Intent(mActivity, ShopMyOrderListActivity.class);
                intent.putExtra("selectPosition", 3);
                startActivity(intent);
                break;
            case R.id.ll_order_3:
                intent = new Intent(mActivity, ShopMyOrderListActivity.class);
                intent.putExtra("selectPosition", 4);
                startActivity(intent);
                break;
            case R.id.ll_order_4:
                skipToActivity(ShopMyOrderListActivity.class);
                break;
            case R.id.ll_about_us:
                skipToActivity(AboutUsActivity.class);
                break;
            case R.id.ll_house:
                skipToActivity(HouseListActivity.class);
                break;
            case R.id.ll_address:
                skipToActivity(AddressListActivity.class);
                break;
            case R.id.ll_setting:
                skipToActivity(SettingActivity.class);
                break;
            case R.id.ll_exit:
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("是否退出登录?");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    outLogin();
                });
                dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
            case R.id.ll_kefu_mobile:
                String tel = tvTelphone.getText().toString();
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("是否拨打" + tel);
                dialogBuild.setPositiveButton("是", v -> {
                    dialogBuild.dismiss();
                    CallPhoneUtil.callPhone(mActivity, tel);
                });
                dialogBuild.setNegativeButton("否", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
        }
    }

    /**
     * 退出登录
     */
    public void outLogin() {
//        ViewLoading.showProgress(mActivity);
//        //解绑DeviceId
//        CloudPushService pushService = PushServiceFactory.getCloudPushService();
//        new MineModelImpl().requestUnBindDeviceId(pushService.getDeviceId(), new DataCallBack<BaseResponseBean>() {
//            @Override
//            public void onSuccessful(BaseResponseBean bean) {
//
//            }
//
//            @Override
//            public void onFailed(String msg, String code) {
//
//            }
//        });
//        //退出登录
//        if (userInfoBean == null) {
//            return;
//        }
//        new MineModelImpl().requestLoginOut(userInfoBean.getData().getId() + "", new DataCallBack<BaseResponseBean>() {
//            @Override
//            public void onSuccessful(BaseResponseBean bean) {
//
//            }
//
//            @Override
//            public void onFailed(String msg, String code) {
//
//            }
//        });
        SPManager.getInstance().logOffRemove();
        Intent intent = new Intent(mActivity, LoginActivity.class);
        startActivity(intent);
        mActivity.finish();
    }
}
